// 常量配置
const MAX_HISTORY_LENGTH = 10
const STORAGE_KEY = 'search_history'

// 从本地存储获取历史记录
const getStorageHistory = () => {
  try {
    const history = uni.getStorageSync(STORAGE_KEY)
    return history ? JSON.parse(history) : []
  } catch (error) {
    console.error('Failed to get search history from storage:', error)
    return []
  }
}

// 保存历史记录到本地存储
const saveStorageHistory = (history) => {
  try {
    uni.setStorageSync(STORAGE_KEY, JSON.stringify(history))
  } catch (error) {
    console.error('Failed to save search history to storage:', error)
  }
}

export default {
  namespaced: true,

  state: {
    history: getStorageHistory()
  },

  mutations: {
    // 添加搜索历史
    addHistory(state, keyword) {
      if (!keyword) return

      // 移除重复项
      const index = state.history.indexOf(keyword)
      if (index > -1) {
        state.history.splice(index, 1)
      }

      // 添加到开头
      state.history.unshift(keyword)

      // 限制长度
      if (state.history.length > MAX_HISTORY_LENGTH) {
        state.history.pop()
      }

      // 保存到本地存储
      saveStorageHistory(state.history)
    },

    // 清空搜索历史
    clearSearchHistory(state) {
      state.history = []
      saveStorageHistory(state.history)
    }
  }
} 